﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Mandelbeep
{
    class Midi
    {
        // Midi
        protected delegate void MidiCallback(int handle, int msg, int instance, int param1, int param2);

        [DllImport("winmm.dll")]
        private static extern int midiOutOpen(ref int handle, int deviceID, MidiCallback proc, int instance, int flags);
        [DllImport("winmm.dll")]
        private static extern int midiOutClose(int handler);
        [DllImport("winmm.dll")]
        protected static extern int midiOutShortMsg(int handle, int message);

        static int _MidiHandler = -1;

        const int NOTEOFF = 0x80;
        const int NOTEON = 0x90;
        const int CTRLCHG = 0xB0;
        const int ALLSOUDNOFF = 0x7800;
        public int DefaultChannel { get; set; }
        public int DefaultVelocity { get; set; }
        public int DefaultLength { get; set; }

        public Midi()
        {
            int r;

            if (_MidiHandler == -1)
                r = midiOutOpen(ref _MidiHandler, 0, null, 0, 0);

            DefaultChannel = 0;
            DefaultVelocity = 0;
            DefaultLength = 100;
        }

        public void Cleanup()
        {
            int result = midiOutClose(_MidiHandler);
        }

        public void PlayNote(int note, int length = -1, int velocity = -1, int channel = -1)
        {
            if (length == -1)
                length = DefaultLength;

            if (velocity == -1)
                velocity = DefaultVelocity;

            if (channel == -1)
                channel = DefaultChannel;

            // Note 60 = middle c
            // NOTE_ON channel 0 = 128, 1 = 129, 2 = 130, etc.
            // noteLength not currently used

            int r;

            r = midiOutShortMsg(_MidiHandler, NOTEON | channel | note << 8 | velocity << 16);

            //_midichannel++;
            //_midichannel = _midichannel % 128;
        }
    }
}
